package com.chookss.home.document;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.adapter.DocunmentListAdapter;
import com.chookss.home.entity.DocunmentEntity;
import com.chookss.tiku.view.FlowLayout;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.tools.old.SignUtils;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import scut.carson_ho.searchview.EditText_Clear;

public class DocumentSearchActivity extends BaseAct {


    @BindView(R.id.et_search)
    EditText_Clear etSearch;
    @BindView(R.id.search_cancle)
    TextView searchCancle;
    @BindView(R.id.llSearch)
    LinearLayout llSearch;
    @BindView(R.id.llvDelele)
    LinearLayout llvDelele;
    @BindView(R.id.llHistory)
    LinearLayout llHistory;
    @BindView(R.id.flowLayout)
    FlowLayout flowLayout;
    @BindView(R.id.rvView)
    RecyclerView rvView;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    private List<String> lists = new ArrayList<>();
    private FlowAdapter adapter;
    private String key = "";
    private DocunmentListAdapter docunmentListAdapter;
    private List<DocunmentEntity> dounmentEntityLists = new ArrayList<>();
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private int type = 0;//0默认搜索状态 1展示单个文档状态学习任务过来的  2发布图文过来的3投屏过来的
    private String dataCode = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_document_search);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        type = getIntent().getIntExtra("type", 0);
        dataCode = getIntent().getStringExtra("dataCode");
        registerBoradcastReceiver();
        etSearch.setHint("请输入资料关键词");
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {   // 按下完成按钮，这里和上面imeOptions对应
                    if (!Utils.isNull(v.getText().toString())) {
                        add(v.getText().toString());
                        key = v.getText().toString();
                        Utils.hideInputKeyboard(DocumentSearchActivity.this, etSearch);
                        llHistory.setVisibility(View.GONE);
                        llNone.setVisibility(View.GONE);
                        srlView.autoRefresh();
                        return false;   //返回true，保留软键盘。false，隐藏软键盘
                    } else {
                        MyToast.show("请输入关键词");
                    }
                }
                return true;   //返回true，保留软键盘。false，隐藏软键盘
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(Utils.isNull(s.toString())){
                    searchCancle.setText("取消");
                }else{
                    searchCancle.setText("搜索");
                }
            }
        });
        String text = new ShareUtils().getString(this,  Utils.getCacheName(this,StaticClass.DOCUMENT_HISTORY), "");
        if (!Utils.isNull(text)) {
            List<String> stringList = JSONArray.parseArray(text, String.class);
            if (stringList != null) {
                lists.addAll(stringList);
            }
            if (lists.size() > 0) {
                // 设置 Adapter
                flowLayout.setVisibility(View.VISIBLE);
                adapter = new FlowAdapter(this, lists);
                flowLayout.setAdapter(adapter);
            }
        }
        rvView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        if (type == 2) {
            docunmentListAdapter = new DocunmentListAdapter(R.layout.item_database_list, this, dounmentEntityLists, 0, 2, null, "DocumentSearchActivity_DownloadFile");
        } else {
            docunmentListAdapter = new DocunmentListAdapter(R.layout.item_database_list, this, dounmentEntityLists, 0, 0, null, "DocumentSearchActivity_DownloadFile");
        }
        ((SimpleItemAnimator) rvView.getItemAnimator()).setSupportsChangeAnimations(false);
        rvView.setAdapter(docunmentListAdapter);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
        if (type == 1 || type == 3) {
            if (type == 1) {
                commonTitleTxt.setText("学习任务");
            } else {
                commonTitleTxt.setText("资料库");
            }
            llSearch.setVisibility(View.GONE);
            llHistory.setVisibility(View.GONE);
            srlView.setEnableLoadMore(false);
            srlView.setEnableRefresh(false);
            Observable.timer(500, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) {
                            try {

                                File SDRootPath2 = new File(getFilesDir() + File.separator + Urls.DOWNLOAD);
                                if (!SDRootPath2.exists()) {
                                    // 按照指定的路径创建文件夹
                                    SDRootPath2.mkdirs();
                                }
                                //清除缓存的空文件
                                FileUtilss.deleteNullFile(SDRootPath2);
                                File SDRootPath3 = new File(getFilesDir() + File.separator + Urls.DOWNLOADCache);
                                if (!SDRootPath3.exists()) {
                                    // 按照指定的路径创建文件夹
                                    SDRootPath3.mkdirs();
                                }
                                FileUtilss.deleteDir2(SDRootPath3);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
            getDataDetail();
            initDownFiles();
        } else {
            srlView.autoRefresh();
            commonTitleTxt.setText("搜索");
        }
    }

    private void initDownFiles() {
        File file = new File(getFilesDir() + File.separator + Urls.DOWNLOAD);
        File[] files = file.listFiles();
        if (files != null) {
            MyApp.downloadFiles.clear();
            for (int i = 0; i < files.length; i++) {
                MyApp.downloadFiles.add(files[i].getName());
            }
        }
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("key", key);
        map.put("pageNum", currentPage + "");
        map.put("pageSize", "20");
        map.put("type", "0");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<DocunmentEntity>>>() {
        }.getType(), null, Urls.searchTopByKey, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<DocunmentEntity>>() {
            @Override
            public void onSuccess(List<DocunmentEntity> data) {
                loadEnd();
                dismissLoading();
//                List<DocumentSearchEntity.ListBean> companyBeanList = data.getList();
                if (srlView == null || llNone == null) {
                    return;
                }
                if (currentPage == 1) {
                    dounmentEntityLists.clear();
                    docunmentListAdapter.notifyDataSetChanged();
                }

                if (data.size() == 0) {
                    isEnd = true;
                    if (dounmentEntityLists.size() == 0) {
                        srlView.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                } else {
                    srlView.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                    dounmentEntityLists.addAll(data);
                    docunmentListAdapter.searchNotifyDataSetChanged(etSearch.getText().toString());
                }

            }

            @Override
            public void onError(String errorMsg) {
                dismissLoading();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getDataDetail() {
        Map<String, String> allmap = new HashMap<>();
        allmap.put("dataCode", dataCode);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<DocunmentEntity>>() {
        }.getType(), null, Urls.getDetail, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<DocunmentEntity>() {
            @Override
            public void onSuccess(DocunmentEntity data) {
                if (data != null) {
                    if (srlView == null || llNone == null) {
                        return;
                    }
                    dounmentEntityLists.clear();
                    srlView.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                    dounmentEntityLists.add(data);
                    docunmentListAdapter.notifyDataSetChanged();
                    if (type == 1) {
                        docunmentListAdapter.setTask();
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh();
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore();
    }


    private void add(String data) {
        // 设置 Adapter
        if (flowLayout == null) {
            return;
        }
        if (!lists.contains(data)) {
            lists.add(data);
            saveSearchHistory();
            // 设置 Adapter
            flowLayout.setVisibility(View.VISIBLE);
            adapter = new FlowAdapter(this, lists);
            flowLayout.setAdapter(adapter);
        }
    }

    private void remove(int position) {
        // 设置 Adapter
        if (flowLayout == null) {
            return;
        }
        lists.remove(position);
        saveSearchHistory();
        // 设置 Adapter
        if (lists.size() > 0) {
            flowLayout.setVisibility(View.VISIBLE);
            adapter = new FlowAdapter(this, lists);
            flowLayout.setAdapter(adapter);
        } else {
            flowLayout.setVisibility(View.GONE);
        }


    }


    private void saveSearchHistory() {
        if (lists.size() > 5) {
            lists.remove(0);
        }
        String text = JSON.toJSONString(lists);
        new ShareUtils().putString(this,  Utils.getCacheName(this,StaticClass.DOCUMENT_HISTORY), text);
    }

    class FlowAdapter extends FlowLayout.Adapter<FlowAdapter.FlowViewHolder> {

        private static final String TAG = "FlowAdapter";

        private Context mContext;
        private List<String> mContentList;

        public FlowAdapter(Context mContext, List<String> mContentList) {
            this.mContext = mContext;
            this.mContentList = mContentList;
        }

        @Override
        public FlowViewHolder onCreateViewHolder(ViewGroup parent) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_document_list, parent, false);
//            // 给 View 设置 margin
            ViewGroup.MarginLayoutParams mlp = new ViewGroup.MarginLayoutParams(view.getLayoutParams());
            int margin = Utils.dip2px(mContext, 6);
            mlp.setMargins(margin, margin, margin, margin);
            view.setLayoutParams(mlp);

            return new FlowViewHolder(view);
        }

        @Override
        public void onBindViewHolder(FlowViewHolder holder, int position) {
            holder.tvTitle.setText(mContentList.get(position));
            holder.ivDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    remove(position);
                }
            });
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    key = mContentList.get(position);
                    etSearch.setText(key);
                    llHistory.setVisibility(View.GONE);
                    llNone.setVisibility(View.GONE);
                    isEnd = false;
                    currentPage = 1;
                    showLoading();
                    getData();
                }
            });
        }

        @Override
        public int getItemCount() {
            return mContentList.size();
        }

        class FlowViewHolder extends FlowLayout.ViewHolder {
            TextView tvTitle;
            ImageView ivDelete;

            public FlowViewHolder(View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tvTitle);
                ivDelete = itemView.findViewById(R.id.ivDelete);
            }
        }
    }

    @OnClick({R.id.common_title_back, R.id.search_cancle, R.id.llvDelele})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
            case R.id.search_cancle:
                if("搜索".equals(searchCancle.getText().toString())){
                    add(etSearch.getText().toString());
                    key = etSearch.getText().toString();
                    Utils.hideInputKeyboard(DocumentSearchActivity.this, etSearch);
                    llHistory.setVisibility(View.GONE);
                    llNone.setVisibility(View.GONE);
                    srlView.autoRefresh();
                }else{
                    finish();
                }

                break;
            case R.id.llvDelele:
                new ShareUtils().putString(this, Utils.getCacheName(this,StaticClass.DOCUMENT_HISTORY), "");
                lists.clear();
                if (flowLayout == null) {
                    return;
                }
                flowLayout.setVisibility(View.GONE);
                break;
        }
    }


    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                int position = intent.getIntExtra("position", 0);
                int percent = intent.getIntExtra("percent", 0);
                String recevierDataCode = intent.getStringExtra("dataCode");
                boolean encryptStatus = intent.getBooleanExtra("encryptStatus", false);
                String fileUrl = intent.getStringExtra("fileUrl");
                String fileName = intent.getStringExtra("fileName");
                for (int i = 0; i < dounmentEntityLists.size(); i++) {
                    if (dounmentEntityLists.get(i).getDataCode().equals(recevierDataCode)) {
                        if (!dounmentEntityLists.get(i).isOpen()) {
                            if(encryptStatus){
                                dounmentEntityLists.get(i).setOpen(true);
                            }
                            dealData(position, percent, recevierDataCode, encryptStatus, fileUrl, fileName);
                        }

                    }
                }
            }
        }

    };

    /**
     * @param position
     * @param percent
     * @param recevierDataCode 处理广播数据
     * @param encryptStatus
     * @param fileUrl
     * @param fileName
     */
    private void dealData(int position, int percent, String recevierDataCode, boolean encryptStatus, String fileUrl, String fileName) {

        if (encryptStatus) {
            if (!MyApp.docunmentOpen) {
                Intent newIntent = new Intent(DocumentSearchActivity.this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                startActivity(newIntent);
                if (type == 1) {
                    finish();
                }
            }
        } else {
            if (percent > 0 && percent < 100) {
                if (docunmentListAdapter != null) {
                    dounmentEntityLists.get(position).setProgress(percent);
                    docunmentListAdapter.notifyItemChanged(position);
                }
            } else if (percent == 100) {
                if (docunmentListAdapter != null) {
                    dounmentEntityLists.get(position).setProgress(100);
                    docunmentListAdapter.notifyItemChanged(position);
                    new Thread() {
                        @Override
                        public void run() {
                            AESEncrypt.encryptFile(DocumentSearchActivity.this, fileUrl, fileName, recevierDataCode, "DocumentSearchActivity_DownloadFile");
                        }
                    }.start();
                }


            }else if (percent == 0) {
                //正常情况不会0
                Intent newIntent = new Intent(this, DocumentPreviewActivity.class);
                newIntent.putExtra("fileUrl", fileUrl);
                newIntent.putExtra("fileName", fileName);
                newIntent.putExtra("dataCode", recevierDataCode);
                newIntent.putExtra("isError", true);
                startActivity(newIntent);
            }
        }
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("DocumentSearchActivity_DownloadFile");// 获取数据
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            HashMap<String, String> map = messageEvent.getHashMap();
            if(map.containsKey("DocumentPreview_error")){
                for (int i = 0; i < dounmentEntityLists.size(); i++) {
                    if (dounmentEntityLists.get(i).getDataCode().equals(map.get("DocumentPreview_error"))) {
                        dounmentEntityLists.get(i).setError(true);

                    }
                }

            }
        } else {
            String msg = messageEvent.getMessage();
            if (!Utils.isNull(msg)) {
                if (msg.equals("TuwenSearchWord_Finish")) {
                    finish();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HashMap<String, DownloadTask> map = MyApp.downloadTaskHashMap;
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
        if (etSearch != null) {
            Utils.hideInputKeyboard(this, etSearch);
        }
    }
}
